package user;

import utils.JdbcUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public class User {
    public static int sum = JdbcUtils.JdbcQuery("SELECT user_id FROM user").size();  //注册人员数目统计
    public static final String user_key_f="whyFi";  //注册管理员账户密钥
    public static final String user_key_s="whySe";  //注册管理员账户密钥
    public static String sql_user_nameQuery = "SELECT user_name FROM user WHERE user_name = ?";
    public static String sql_add_user="INSERT INTO user(user_id,user_name,user_password,user_power,user_create_time,user_lastup_time) VALUES (?,?,?,?,?,?)";
    private static final String sql="SELECT user_name,user_password FROM user WHERE user_name = ? AND user_password = ?";
    //注册密钥检测
    public static boolean key_detection(String key){
        return key.equals(User.user_key_f)||key.equals(User.user_key_s);
    }
    //用户注册
    public static boolean user_queryYn(String name){
        return !JdbcUtils.JdbcQuery(sql_user_nameQuery,name).isEmpty();
    }
    public static boolean ADD_user(String name,String password,int power){
        LocalDateTime time=LocalDateTime.now();
        return JdbcUtils.JdbcUpdate(sql_add_user,User.sum+1,name,password,power,time,time)>=1;
    }
    //登录
    public static boolean login(String username,String password){
        return !JdbcUtils.JdbcQuery(sql,username,password).isEmpty();
    }
    public static String sql_query="SELECT * FROM user WHERE user_name = ?";
    public static String sql_lowpoer_query="SELECT user_name FROM user WHERE user_power = 2";
    public static String sql_updata_password="UPDATE user SET user_password = ?  WHERE user_name = ?";
    public static String sql_delete_user="DELETE FROM user WHERE user_name = ?";
    public static String sql_updata_lasttime="UPDATE user SET user_lastup_time = ? WHERE user_name = ?";
    public static void idChange(){
        String sql = "SELECT * FROM user ORDER BY user_id ASC";
        List<Map<String, Object>> rs = JdbcUtils.JdbcQuery(sql);
        int newId = 1;
        for(Map<String,Object> map : rs){
            for(String key : map.keySet()) {
                if (key.equals("user_id")){
                    int oldId = (int) map.get(key);
                    String updateSql = ("UPDATE user SET user_id = " + newId +" WHERE user_id = " + oldId);
                    JdbcUtils.JdbcUpdate(updateSql);
                    newId++;
                }
            }
        }
    }
}
